package com.haidechizi.i18n.code.generator.common.message.generator;



import com.haidechizi.i18n.code.generator.common.message.constants.CodeGeneratorTypeConstants;
import com.haidechizi.i18n.code.generator.common.message.utils.FileTypeUtils;
import com.haidechizi.i18n.code.generator.common.message.utils.FileUtils;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JavaStaticCodeGenerator extends BaseCodeGenerator {


    private ThreadLocal<Map<String, String>> enumCnDataMap = new ThreadLocal() {

        @Override
        protected Object initialValue() {
            return new HashMap<>();
        }
    };


    private static final String suffix = "java";


    @Override
    protected String generateKey(String cnData, String fileSuffix, String content) {
        return keyGeneratorAdapter.generatorKey(cnData, fileSuffix, content);
    }

    @Override
    protected String generateResourceData(String cnData, String content, Matcher matcher, String fileSuffix) {
        if (FileTypeUtils.isEnum(suffix, content)) {
            Pattern pattern = Pattern.compile("[^\\n]*" + cnData + "*[^\\n]");
            Matcher matcher1 = pattern.matcher(content);
            if (matcher1.find()) {
                return matcher1.group();
            }
        }
        return super.generateResourceData(cnData, content, matcher, fileSuffix);
    }

    @Override
    protected String generateReplaceData(String key, String cnData, String content, String fileSuffix) {
        if (FileTypeUtils.isEnum(suffix, content)) {
            Pattern pattern = Pattern.compile("[^\\n]*" + cnData + "*[^\\n]");
            Matcher matcher = pattern.matcher(content);
            if (matcher.find()) {
                String group = matcher.group();
                StringBuilder sb = new StringBuilder();
                sb.append("    @I18nKey(\"" + key + "\")").append("\n");
                // 将enum中的中文替换掉，之后再进行还原
                String tempKey = "@enun" + getAndAdd() + "@";
                sb.append(group.replace(cnData, tempKey));
                // 将其添加到ThreadLocal变量中
                enumCnDataMap.get().put(tempKey, cnData);
                return sb.toString();
            }
        }
        return "I18nStaticInfoUtil.translate(\"" + key + "\")";
    }

    @Override
    public void createPropertiesFile(String path) {
        Map<String, Map<String, String>> languageMap = languageMessageMap.get();
        if (languageMap == null || languageMap.isEmpty()) {
            return;
        }
        Map<String, Properties> map = new HashMap<>();
        for (Map.Entry<String, Map<String, String>> entry : languageMap.entrySet()) {
            // 配置文件key
            String key = entry.getKey();
            Map<String, String> value = entry.getValue();
            for (Map.Entry<String, String> languageEntry : value.entrySet()) {
                String language = languageEntry.getKey();
                String translate = languageEntry.getValue();
                Properties properties = null;
                if (map.containsKey(language)) {
                    properties = map.get(language);
                } else {
                    properties = new Properties();
                    map.put(language, properties);
                }
                properties.put(key, translate);
            }
        }
        // 获取当前文件的路径
        File file = new File(path);
        String filePath = file.getPath().replace(file.getName(), "");

        for (Map.Entry<String, Properties> entry : map.entrySet()) {
            String language = entry.getKey();
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<Object, Object> dataEntry : entry.getValue().entrySet()) {
                sb.append(dataEntry.getKey()).append("=").append(FileUtils.chinaToUnicode(dataEntry.getValue().toString())).append("\n");
            }
            FileUtils.createFile(sb.toString(), filePath + "message_" + language, ".properties");
        }

    }

    /**
     * 类型
     * 1.java静态资源国际化
     * 2.前端静态资源国际化
     * 3.后端动态资源国际化
     *
     * @return
     */
    @Override
    public String type() {
        return CodeGeneratorTypeConstants.JAVA_STATIC;
    }

    /**
     * 是否支持当前文件类型
     *
     * @param fileType
     * @return
     */
    @Override
    public boolean isSupport(String fileType) {
        return suffix.equals(fileType);
    }

    /**
     * 后置处理器
     *
     * @param content
     * @param path
     * @return
     */
    @Override
    protected String afterTranslate(String content, String path) {
        Map<String, String> stringMap = enumCnDataMap.get();
        for (Map.Entry<String, String> entry : stringMap.entrySet()) {
            content = content.replace(entry.getKey(), entry.getValue());
        }
        // 清空字符
        enumCnDataMap.get().clear();
        return content;
    }
}
